package com.my.core;

import com.my.annotation.Instance;
import com.my.annotation.AutoDi;

import java.io.File;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class ApplicationContext {
    private Map<String, Object> beans = new HashMap<>();
    private Map<Class<?>, Object> interfaceToBeanMap = new HashMap<>();

    public ApplicationContext(String basePackage) {
        try {
            // 包扫描规则
            String path = basePackage.replace(".", "/");
            URL url = Thread.currentThread().getContextClassLoader().getResource(path);
            if (url == null) {
                System.out.println("URL is null for path: " + path);
                return;
            }
            File dir = new File(url.toURI());
            if (!dir.exists()) {
                System.out.println("Directory does not exist: " + dir.getAbsolutePath());
                return;
            }
            // 递归扫描包路径
            classLoader(dir, basePackage);

            // 构建接口到实现类的映射
            for (Object bean : beans.values()) {
                Class<?> clazz = bean.getClass();
                for (Class<?> iface : clazz.getInterfaces()) {
                    interfaceToBeanMap.put(iface, bean);
                }
            }

            // 依赖注入
            for (Object bean : beans.values()) {
                Field[] fields = bean.getClass().getDeclaredFields();
                for (Field field : fields) {
                    if (field.isAnnotationPresent(AutoDi.class)) {
                        field.setAccessible(true);
                        Class<?> fieldType = field.getType();
                        Object dependency = interfaceToBeanMap.get(fieldType);
                        if (dependency == null) {
                            System.out.println("Dependency not found for field: " + field.getName());
                        } else {
                            field.set(bean, dependency);
                            System.out.println("Dependency injected for field: " + field.getName());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void classLoader(File dir, String basePackage) throws Exception {
        File[] files = dir.listFiles();
        if (files == null) {
            System.out.println("No files found in directory: " + dir.getAbsolutePath());
            return;
        }
        for (File file : files) {
            if (file.isDirectory()) {
                // 递归扫描子目录
                classLoader(file, basePackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                // 处理类文件
                String className = basePackage + "." + file.getName().replace(".class", "");
                Class<?> clazz = Class.forName(className);
                if (clazz.isAnnotationPresent(Instance.class)) {
                    Object bean = clazz.getDeclaredConstructor().newInstance();
//                    String beanName = clazz.getSimpleName().toLowerCase();
                    String simpleName = clazz.getSimpleName();
                    String beanName = simpleName.substring(0, 1).toLowerCase() + simpleName.substring(1);
                    beans.put(beanName, bean);
                    System.out.println("Bean created: " + beanName);
                }
            }
        }
    }

    public Object getBean(String beanName) {
        return beans.get(beanName);
    }
}
